import { defineStore } from 'pinia'
import { getCustomers, addCustomer, updateCustomer, deleteCustomer, importCustomers } from '@/api/customer'

export const useCustomerStore = defineStore('customer', {
  state: () => ({
    customers: [],
    currentCustomer: null
  }),
  actions: {
    async fetchCustomers(params = {}) {
      const res = await getCustomers(params)
      this.customers = res.data
      return res
    },
    async createCustomer(data) {
      const res = await addCustomer(data)
      this.customers.unshift(res.data)
      return res
    },
    async updateCustomer(id, data) {
      const res = await updateCustomer(id, data)
      const index = this.customers.findIndex(c => c.id === id)
      if (index !== -1) {
        this.customers[index] = res.data
      }
      return res
    },
    async deleteCustomer(id) {
      await deleteCustomer(id)
      this.customers = this.customers.filter(c => c.id !== id)
    },
    async importCustomers(file) {
      const res = await importCustomers(file)
      this.customers = [...res.data, ...this.customers]
      return res
    }
  },
  getters: {
    activeCustomers: (state) => state.customers.filter(c => c.status === 1),
    vipCustomers: (state) => state.customers.filter(c => c.level === 'VIP')
  }
})